import sys

from PyQt5.QtCore import QSize
from PyQt5.QtGui import QStandardItemModel, QPixmap, QStandardItem
from PyQt5.QtWidgets import QApplication, QLabel
from bs4 import BeautifulSoup
import requests
from App import InfoTableView


class MovieInfoTableView(InfoTableView):

    def __init__(self, pageSize = 10, pageNo = 1):
        super().__init__(pageSize, pageNo)
        self.setWindowTitle("豆瓣电影 Top 250")
        self.model = QStandardItemModel(self.pageSize, 5)
        self.model.setHorizontalHeaderLabels(["电影名", "简述", "导演/主演", "评分", "海报"])
        self.tableView.setModel(self.model)

    def loadPage(self):

        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'
        }
        resp = requests.get('https://movie.douban.com/top250?start=%d&filter=' % (self.pageSize * (self.pageNo - 1)), headers=header)
        if resp.status_code != 200:
            return
        resp.encoding = 'utf-8'
        soup = BeautifulSoup(resp.text, 'html.parser')
        movies = soup.find('ol', class_='grid_view').find_all('li')
        print(movies)

        row = 0
        for m in movies:
            pic = m.find('div', class_='pic')
            infohd = m.find('div', class_='hd')
            infobd = m.find('div', class_='bd')
            item = QStandardItem(infohd.a.find('span').text)
            self.model.setItem(row, 0, item)
            item = QStandardItem(infobd.find('span', class_='inq').text)
            self.model.setItem(row, 1, item)
            item = QStandardItem(infobd.find('p').text)
            self.model.setItem(row, 2, item)
            item = QStandardItem(infobd.find('span', class_='rating_num').text)
            self.model.setItem(row, 3, item)

            resp = requests.get(pic.a.img['src'])
            img = QPixmap()
            img.loadFromData(resp.content)
            label = QLabel()
            label.setPixmap(img);
            item = QStandardItem(infobd.find('p').text)
            item.setSizeHint(QSize(img.width(), img.height()))
            index = self.model.index(row, 4)
            self.tableView.setIndexWidget(index, label)
            row += 1

        self.tableView.resizeRowsToContents()
        self.tableView.resizeColumnsToContents()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = MovieInfoTableView(25, 1)
    win.loadPage()
    win.show()
    sys.exit(app.exec_())
